
<!DOCTYPE html>
<html>
   <head>
      <title>BridgeIt  GeoTrack </title>
      <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
      <link rel="icon" type="image/png" href="favicon.png"/>
      <meta name="apple-mobile-web-app-capable" content="yes" />
      
      <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,600,300,400' rel='stylesheet' type='text/css'/>
      <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
      <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css"/>
      <link rel="stylesheet" href="http://bridgeit.github.io/demo-jqm/css/mobile.css" type="text/css"/>
      <link rel="stylesheet" href="http://bridgeit.github.io/demo-jqm/css/syntax.css" type="text/css"/>
      
      <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=true&libraries=geometry"></script>
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
      <script type="text/javascript" src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
      
      <!-- bridgeit.js UNSTABLE VERSION -->
      <script type="text/javascript" src="http://bridgeit.github.io/bridgeit.js/src/bridgeit.js"></script>
      <!--
      <script type="text/javascript" src="http://api.bridgeit.mobi/bridgeit/bridgeit.js"></script-->      
      <script type="text/javascript" src="http://bridgeit.github.io/demo-jqm/javascript/bridgeit-demos.js"></script>
        
   </head>

<body>
    <div data-role="page" id="geotrack" >  
        	<div data-role="header" class="hdr demo" data-id="header">
	    <a class="btnBack" href="./index.html" data-dom-cache="true"
	    	data-transition="slide" data-direction="reverse" >
	    	<i class="icon-chevron-left"></i>
	    </a>
	    <h1><span class="bridge-font-color">BridgeIt</span></h1>
	</div>

        <div data-role="content">
            <div id="geotrack" title="Locate It" class="panel" onfocus="geoTrackVisible();">
    <script>
        $(document).on("pageshow", "#geotrack", function () {
            geoTrackVisible();
        });
    </script>
    <h2>GeoTrack Location Tracking</h2>
    <fieldset class="desc">
        <div class="row">
            <p class="normalText">
                Press the 'Start Tracking' button and have BridgeIt track your location. After tracking 
                has started, you can continue with other activities and come back to see your track. 
            </p>
        </div>
        <div class="row shown-xs">
<div class="highlight"><pre><code class="javascript"><span class="nx">bridgeit</span><span class="p">.</span><span class="nx">geoTrack</span><span class="p">(</span><span class="s1">&#39;myId&#39;</span><span class="p">,</span> 
  <span class="nx">callback</span><span class="p">,</span> <span class="nx">options</span><span class="p">);</span>
</code></pre></div>
        </div>
        <div class="row hidden-xs">
<div class="highlight"><pre><code class="javascript"><span class="nx">bridgeit</span><span class="p">.</span><span class="nx">geoTrack</span><span class="p">(</span><span class="s1">&#39;myId&#39;</span><span class="p">,</span> <span class="nx">callback</span><span class="p">,</span> <span class="nx">options</span><span class="p">);</span>
</code></pre></div>
        </div>
    </fieldset>
    
    <a id="startTrackingBtn" data-role="button" class="btn" style="display: none"
        onclick="bridgeit.geoTrack('tracker','onAfterTrackingStarted', {postURL: window.echoHub + 'list/geotrack-' + bridgeit.getId(), strategy:'significant',duration:0.3,_jguid:bridgeit.getId()});">Start Tracking</a>
    <a id="stopTrackingBtn" data-role="button" class="btn" style="display: none"
        onclick="bridgeit.geoTrack('tracker','onAfterTrackingStopped', {postURL: window.echoHub + 'list/geotrack-' + bridgeit.getId(), strategy:'stop',_jguid:bridgeit.getId()});">
        Stop Tracking
        <i class="icon-gear icon-spin geotracking"></i>
    </a>

    <h4>Location Updates</h4>
    <div id="geoTrackPushUpdates" class="geotrack-updates">
        <table id="geoTrackPushUpdatesHdr" class="hdr">
            <thead>
                <th>Time</th><th>Latitude</th><th>Longitude</th><th>Accuracy</th>
            </thead>
            <tbody>

            </tbody>
        </table>
        <div class="data">
            <table id="geoTrackPushUpdatesTbl">
                <tbody>

                </tbody>
            </table>
        </div>
    </div>

    <div id="trackMapCanvas" style="height:200px"></div>
    <div id="trackMapOverlay" >
        <span id="trackMapDetail" style="background-color:white"></span>
    </div>
    <script type="text/javascript">
    window.geoTracking = false;
    
    var geoPushReady;

    function isGeoTrackRunning(){
        var result = false;
        if( window.localStorage && localStorage.getItem('bridgeit.geoTrackRunning') === 'true'){
            result = true;
        }
        return result;
    }

    function setGeoTrackRunning(running){
        if( window.localStorage ){
            localStorage.setItem('bridgeit.geoTrackRunning', running);
        }
        refreshGeoTrackButtons(running);
    }

    function refreshGeoTrackButtons(running){
        document.getElementById('startTrackingBtn').style.display = running ? 'none' : '';
        document.getElementById('stopTrackingBtn').style.display = running ? '' : 'none';
    }

    refreshGeoTrackButtons(isGeoTrackRunning());
    
    if (!geoPushReady)  {
        bridgeit.usePushService( window.pushHub, window.apiKey);
        bridgeit.addPushListener("geotrack-" + bridgeit.getId(),
                "onReceiveGeoTrackPush");
        geoPushReady = true;
    }

    function onReceiveGeoTrackPush(){
        console.log("geotrack Push received");
        updateMarkers();
    }

    function addLocationUpdateRow(geojson){
        if( geojson ){
            var updatesTbl = document.getElementById('geoTrackPushUpdatesTbl');
            var updateRow = updatesTbl.insertRow(0);
            
            var timeCell = updateRow.insertCell(0);
            var timeProp = getTimestampFromGeoJson(geojson);
            if( timeProp ){
                var time = new Date(timeProp);
                var timeString = dateTimeStringFromDate(time);
                timeCell.innerHTML = '<span>' + timeString + '</span>';
                updateRow.style.backgroundColor = colorFromTimestamp(timeProp);

            }

            var latCell = updateRow.insertCell(1);
            var lat = geojson.geometry.coordinates[1];
            latCell.innerHTML = '<span>' + lat.toFixed(4) + '</span>';

            var lngCell = updateRow.insertCell(2);
            var lng = geojson.geometry.coordinates[0];
            lngCell.innerHTML = '<span>' + lng.toFixed(4) + '</span>';

            var accuracyCell = updateRow.insertCell(3);
            if (geojson.properties.accuracy)  {
                accuracyCell.innerHTML = '<span>' + geojson.properties.accuracy.toFixed(0) + 'm</span>';
            } else {
                accuracyCell.innerHTML = '<span></span>';
            }

            updateRow.addEventListener('click', function(){ 
                moveCursorMarker(lat,lng); 
                var prev = document.querySelector('.geotrack-updates .active');
                if( prev ){
                    prev.classList.remove('active');
                }
                this.classList.add('active');
            }, false);
        }
    }

    function onAfterTrackingStarted()  {
        console.log('geoTrack onAfterTrackingStarted');
        setGeoTrackRunning(true);
    }

    function onAfterTrackingStopped(){
        console.log('geoTrack onAfterTrackingStopped');
        setGeoTrackRunning(false);
    }

    function geoTrackVisible()  {
        initTrackMap();
        setTimeout( function(){
            google.maps.event.trigger(geoTrackMap, 'resize');
            updateMarkers();
        },1000);
    }

    var geoTrackMap;
    var geoTrackMapMarkers = [];

    function initTrackMap() {
        console.log('geoTrack initTrackMap');
        if( !window.geoTracking ){
            window.geoTracking = true;
            var mapOptions = {
                center: new google.maps.LatLng(-34.397, 150.644),
                maxZoom: 20,
                zoom: 8,
                draggable: false,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            geoTrackMap = new google.maps.Map(document
                    .getElementById('trackMapCanvas'), mapOptions);
            var overlay = document.getElementById('trackMapOverlay');
            geoTrackMap.controls[google.maps.ControlPosition.RIGHT_TOP]
                    .push(overlay);
        }
    }

    function updateMarkers()  {
        console.log('geoTrack updateMarkers');
        ajaxGet(window.echoHub + 'list/geotrack-' + bridgeit.getId(), processMarkers);
    }

    function getTimestampFromGeoJson(geojson){
        var timeProp;
        if( geojson.properties && geojson.properties.time ){
            timeProp = geojson.properties.time;
        }
        else if( geojson.properties && geojson.properties.timestamp ){
            timeProp = geojson.properties.timestamp;
        }
        return timeProp;
    }

    function colorFromTimestamp(time){
        var hexString = time.toString(16).slice(-6);
        var rgb = [];
        //allow only lighter colors for readability
        rgb[0] = parseInt("0x"+hexString.slice(-6,-4));
        rgb[1] = parseInt("0x"+hexString.slice(-4,-2));
        rgb[2] = parseInt("0x"+hexString.slice(-2));
        
        for( var i = 0 ; i < 3; i++ ){
            if( rgb[i] < 128 ){ 
                rgb[i] += 128;
                rgb[i] = ('00'+rgb[i].toString(16)).slice(-2);
            }
        }
        var color = '#';
        for( var i = 0 ; i < 3; i++ ){
            color += ('00'+rgb[i].toString(16)).slice(-2);
        }
        return color;
    }

    function randomColor() {
        var letters = '0123456789ABCDEF'.split('');
        var color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.round(Math.random() * 15)];
        }
        return color;
    }
    var cursorMarker = new google.maps.Marker({
        position: new google.maps.LatLng(0, 0),
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            strokeColor: '#FF0000',
            scale: 5
        }
    });

    function moveCursorMarker(lat,lng){
        cursorMarker.setPosition(new google.maps.LatLng(lat,lng));
        cursorMarker.setMap(geoTrackMap);
        console.log('moved cursorMarker to ' + lat + ',' + lng);
    }

    function processMarkers(data)  {
        console.log('geoTrack processMarkers: data='+ data);
        if (data){
            var markerData = JSON.parse(data);
            var len = markerData.length;
            var markersPlaced = false;
            var locations = {};
            var locationKeys = [];
            var markerIdx = -1;
            var markerIdxLgth = len;
            for (var i = 0; i < len; i++) {
                
                //google maps follows english usage LatLang
                //rather than standard x,y coordinate longitude,latitude
                var coordinates = markerData[i].geometry.coordinates;
                var location = new google.maps.LatLng(
                        coordinates[1], coordinates[0]);
                var locationKey = markerData[i].properties.jguid;
                if( !locationKey ){
                    locationKey = '999999'; //when no jguid available just use medium gray
                }
                if( locationKeys.indexOf(locationKey) < 0 ){
                    locationKeys.push(locationKey);
                    locations[locationKey] = [];
                }
                var ts = getTimestampFromGeoJson(markerData[i]);  
                
                //check if provided marker is too close to existing marker
                var existLen = geoTrackMapMarkers.length;
                var minDistance = 100;
                for (var j = 0; j < existLen; j++)  {
                    var distance = google.maps.geometry.spherical
                            .computeDistanceBetween (location, 
                            geoTrackMapMarkers[j].position);
                    if (distance < minDistance)  {
                        minDistance = distance;
                    }
                }
                if (minDistance < 5)  {
                    markerIdxLgth--;
                    continue;
                }
                markerIdx++;
                locations[locationKey].push(location);
                addLocationUpdateRow(markerData[i]);

                markersPlaced = true;
                var markerColor = colorFromTimestamp(ts);
                /*
                if( markerIdx == 0 ){
                    markerColor = '#00FF00';
                }
                else if( markerIdx == markerIdxLgth-1){
                    markerColor = '#FF0000';
                }*/
                var marker = new google.maps.Marker({
                    position: location,
                    icon: {
                        path: google.maps.SymbolPath.CIRCLE,
                        strokeColor: markerColor,
                        scale: 4
                    },
                    map: geoTrackMap
                });
                geoTrackMapMarkers.push(marker);

                document.getElementById("trackMapDetail").innerHTML =
                    coordinates[0].toFixed(2) + "," +
                    coordinates[1].toFixed(2) + " " +
                    (coordinates[2] ? ( coordinates[2].toFixed(2) + "m  " ) : "");
            }

            if (markersPlaced)  {
                var existLen = geoTrackMapMarkers.length;
                var bounds = new google.maps.LatLngBounds();
                for (var j = 0; j < existLen; j++)  {
                    bounds.extend(geoTrackMapMarkers[j].position);
                }
                geoTrackMap.fitBounds(bounds);
                //zoom out a bit if only one marker
                if( existLen === 1 ){
                    geoTrackMap.setZoom(10);
                }
                for( var k = 0 ; k < locationKeys.length ; k++ ){
                    var markerColor = "#" + locationKeys[k].substring(0,6);
                    var path = new google.maps.Polyline({
                        path: locations[locationKeys[k]],
                        geodesic: true,
                        strokeColor: markerColor,
                        strokeOpacity: 0.5,
                        strokeWeight: 1
                    });
                    path.setMap(geoTrackMap);

                }
                
            }
            
        }
        else{
            console.log('no data for geotrack...');
        }
    }

    </script>
</div>

        </div>
        	<div data-role="footer" data-id="footer" > 
	    <a href="#" class="icesoft-link" data-role="none">
	        <img src="images/icesoft-logo-bw-2x.png"/>
	    </a>
		<div class="copyright">&copy;&nbsp;2002-2013 ICEsoft Technologies Inc. All rights reserved.</div>
		<a href="https://github.com/bridgeit" data-role="none"><i class="icon-github"></i></a>
		<a href="https://twitter.com/BridgeItApp" data-role="none"><i class="icon-twitter-sign"></i></a>
		<a href="https://www.facebook.com/bridgeitmobi" data-role="none"><i class="icon-facebook-sign"></i></a>
	</div> 
        <script type="text/javascript">
        setMinContentHeight();
        $(document).bind('pageshow', setMinContentHeight);
        $(window).bind('orientationchange', setMinContentHeight);
        $(window).bind('resize', setMinContentHeight);
        </script>
    </div>
    <div id="getBridgeItPopup" style="opacity: 0;display:none;" class="ui-body-c">
        <a id="closeGetBridgePopup" onclick="closeGetBridgeItPopup();"><i class="icon-remove-sign"></i></a>
        <p>Missing BridgeIt native features..would you like to download the BridgeIt utility app now?</p>
        <a id="appStoreLink" href="http://www.icesoft.org/projects/ICEmobile/containers.jsf"
            class="whiteButton bridgeItBtn" onclick="return closeGetBridgeItPopup();" target="_blank">Download the utility app now</a>
    </div>
</body>
</html>